import io
import time
import stat
import yaml
import socket
import re
from django.conf import settings
import traceback

import logging


logger = logging.getLogger('XApiTestServer')


def get_time_stamp():
    ct = time.time()
    local_time = time.localtime(ct)
    data_head = time.strftime("%Y-%m-%d %H-%M-%S", local_time)
    data_secs = (ct - int(ct)) * 1000
    time_stamp = "%s-%03d" % (data_head, data_secs)
    return time_stamp

def update_yaml_file(yaml_file):
    with open(yaml_file,  encoding='utf-8') as pf:
        f_content = yaml.load(pf)
        test_map = f_content[1]

        for f in f_content:
            print(f)

def get_value_from_list(key_value_list, key, default=''):
    """
    :从字典列表中找出对应Key的值
    :param key_value_list: [dict, dict...]
    :param key: 需要查找的key
    :param default: default value
    :return: 返回对应key 的值，如果没有找到，则返回默认值
    """
    for kv in key_value_list:
        if key in kv.keys():
            return kv[key]
    else:
        return default

def get_server_ip_port():
    """
    获取当前服务器的IP
    :return:  当前服务器的IP
    """
    ip = ''
    port = ''
    try:
        ip = settings.SERVER_IP
    except:
        pass
    try:
        port = settings.SERVER_PORT
    except:
        pass
    if not ip:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
        finally:
            s.close()
    if not port:
        port = '80'
    return ip, port

def get_server_base_url():
    ip = '127.0.0.1'
    port = '8000'
    if not settings.DEBUG:
        ip, port = get_server_ip_port()
    base_url = 'http://{}:{}'.format(ip, port)
    return base_url
